/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.srwl.mytx.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.huantansheng.easyphotos.utils.Color.ColorUtils;
import com.huantansheng.easyphotos.utils.system.SystemUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.InviteExtraInfo;
import com.srwl.mytx.fragment.ConversationListFragment;
import com.srwl.mytx.fragment.GaoDeMapFragment;
import com.srwl.mytx.fragment.LiveListFragment;
import com.srwl.mytx.fragment.ProfileFragment;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.BadgerUtil;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.widget.BottomBar;
import com.srwl.mytx.widget.BottomSheetBehaviorV1;
import com.srwl.mytx.widget.BottomTopicList;
import com.srwl.mytx.widget.BottomTopicListV1;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.List;

import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

//import com.srwl.mytx.fragment.BaiDuMapFragment;


@SuppressLint("NewApi")  //屏蔽一切因版本而导致新api中才能使用的方法报的android lint错误
public class MainActivity extends BaseActivity implements PermissionsUtils.IPermissionsResult {

    protected static final String TAG = "MainActivity";
    //private ViewGroup rootLayout; //以后再做，动态加载  BottomTopicList
    private BottomBar bottomBar;
//    private BottomTopicList bottomTopicList;
    private BottomTopicListV1 bottomTopicListV1;
    private ProfileFragment profileFragment;
    private GaoDeMapFragment gaoDeMapFragment;
    // private BaiDuMapFragment baiDuMapFragment;
    private ConversationListFragment conversationListFragment;
    private LiveListFragment liveListFragment;
    private android.app.AlertDialog.Builder conflictBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountLockDialogShow;
    private BroadcastReceiver broadcastReceiver;
    private LocalBroadcastManager broadcastManager;
    private Fragment[] fragments;
    private int currentTabIndex;
    public boolean isConflict = false;
    private long exitTime = 0;
    private boolean isStartingCall;
    private static final int SHOW_MAP_FRAGMENT_FLAG = 0;
    private static final int SHOW_HOME_PAGE_TEXT_FRAGMENT_FLAG = 1;
    private boolean isAccountLock;
    private BottomSheetBehaviorV1 bottomSheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            //  StatusBarCompat.setStatusBarColor(this, Color.parseColor("#f9f9f9"), true);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                Intent intent = new Intent();
                intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
            int statusColor = ContextCompat.getColor(this, R.color.colorPrimaryDark);
            if (ColorUtils.isWhiteColor(statusColor)) {
                SystemUtils.getInstance().setStatusDark(this, true);
            }
        }

//        if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
//            Helper.getInstance().logout();
//            finish();
//            startActivity(new Intent(this, LoginActivity.class));
//            return;
//        } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
//            finish();
//            startActivity(new Intent(this, LoginActivity.class));
//            return;
//        }
        setContentView(R.layout.activity_main);

        initView();   //获取bottomBar和bottomTopicList的引用
        initBottomSheetBehavior();
        // userBindAccount();

        if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_LOCK, false) && !isAccountLockDialogShow) {
            showAccountLock();
        }
        gaoDeMapFragment = new GaoDeMapFragment();
        gaoDeMapFragment.setBottomTopicList(bottomTopicListV1);
        conversationListFragment = new ConversationListFragment();
        liveListFragment = new LiveListFragment();
        profileFragment = new ProfileFragment();


        FragmentManager supportFragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = supportFragmentManager.getFragments();

        //避免mainActivity 奔溃（或者被系统杀死）重建，fragment 重复
        if (fragments.size() != 0) {

            Log.i(TAG, "onCreate: activity 重建了,fragments的数量： " + fragments.size());
            for (int i = 0; i < fragments.size(); i++) {
                Fragment fragment = fragments.get(i);
                Log.i(TAG, "onCreate: " + fragment.getClass().getSimpleName());

                //删除崩溃恢复的fragment 不科学，
                //   supportFragmentManager.beginTransaction().remove(fragment).commit();

                if (fragment instanceof GaoDeMapFragment) {
                    gaoDeMapFragment = (GaoDeMapFragment) fragment;
                    // gaoDeMapFragment = (BaiDuMapFragment) fragment;
                    Log.i(TAG, "onCreate: 地图页面被重建了，");
                } else if (fragment instanceof ConversationListFragment) {
                    conversationListFragment = (ConversationListFragment) fragment;
                    Log.i(TAG, "onCreate: HomePageTextFragment页面被重建了，");

                } else if (fragment instanceof LiveListFragment) {
                    liveListFragment = (LiveListFragment) fragment;
                    Log.i(TAG, "onCreate: LiveListFragment页面被重建了，");

                } else if (fragment instanceof ProfileFragment) {
                    profileFragment = (ProfileFragment) fragment;
                    Log.i(TAG, "onCreate: SettingsFragment页面被重建了，");

                }

            }
        } else {

            supportFragmentManager.beginTransaction().add(R.id.fragment_container, gaoDeMapFragment)
                    .add(R.id.fragment_container, liveListFragment).hide(liveListFragment).show(gaoDeMapFragment)
                    .commit();
        }
        this.fragments = new Fragment[]{gaoDeMapFragment, conversationListFragment, liveListFragment, profileFragment};

        IMSClientBootstrap.getInstance().addImListener(new IMSClientBootstrap.ImListener() {
            @Override
            public void onUnreadCountChange(int totalUnReadCount) {
                //conversationListFragment.updateNoticeUnreadText();
                if (currentTabIndex != 1) {
                    updateUnreadLabel(totalUnReadCount);
                }
                //因为有些 手机点击桌面图片，并不会清空角标（小米就会自动清空），而这一类手机，除了在app 内未读数变为0，找不到去重置桌面角标的时机，
                // 如果只在app 处于后台才去设置角标，会导致 桌面上的未读数和app 内显示的内部一致
                BadgerUtil.addBadger(MainActivity.this, totalUnReadCount);

//                //如果是清空，不管是app 是否在后台，都去更新
//                if (totalUnReadCount == 0) {
//                    BadgerUtil.addBadger(MainActivity.this, totalUnReadCount);
//                } else if (MyApplication.activityCount == 0) {//app 在后台，才去显示桌面角标
//                    BadgerUtil.addBadger(MainActivity.this, totalUnReadCount);
//                }

            }
        });
        registerBroadcastReceiver();
        initTabClickListener();
        Helper.getInstance().checkUpdate(this);
    }


    private void initBottomSheetBehavior() {
        bottomSheetBehavior = BottomSheetBehaviorV1.fromv1(bottomTopicListV1);
        bottomSheetBehavior.setHideable(true);
        //设置默认先隐藏
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        bottomTopicListV1.setBottomSheetBehavior(bottomSheetBehavior);
    }

    @TargetApi(23)
    private void requestPermissions() {
//        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
//            @Override
//            public void onGranted() {
////				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
//                Log.i(TAG, "onGranted: 权限全部通过");
//            }
//
//            @Override
//            public void onDenied(String permission) {
//                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
//                Log.i(TAG, "onDenied: 权限被拒绝 permission： " + permission);
//            }
//        });

    }

    /**
     * setupView views
     */
    private void initView() {
        // rootLayout = findViewById(R.id.root_layout);
        bottomBar = findViewById(R.id.bottom_bar);
        bottomTopicListV1 = findViewById(R.id.bottom_topic_list);
    }


    private void initTabClickListener() {
        bottomBar.setOnTabSelectListener(new BottomBar.OnTabSelectListener() {
            @Override
            public void onTabSelected(int tabId) {
                switch (tabId) {
                    case R.id.ll_world:
                        selectFragment(0);
                        //bottomBar.getCurrentTab().setSelected(true);
                        break;
                    case R.id.ll_conversation:
                        selectFragment(1);
                        //bottomBar.getCurrentTab().setSelected(true);
                        break;
                    case R.id.ll_live:
                        selectFragment(2);
                        // bottomBar.getCurrentTab().setSelected(true);
                        break;
                    case R.id.ll_profile:
                        selectFragment(3);
                        // bottomBar.getCurrentTab().setSelected(true);
                }
            }
        });


    }

    private void selectFragment(int index) {
        if (currentTabIndex == index) {
            Log.i(TAG, "selectFragment: currentTabIndex：" + currentTabIndex + " index:" + index);
            return;
        }
        //如果是从会话列表的fragment 切换到其他fragment,更新未读标签
        if (currentTabIndex == 1) {
            updateUnreadLabel();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //不能用.replace(),切换 屏幕会闪动
        transaction.hide(fragments[currentTabIndex]);
        if (!fragments[index].isAdded()) {
            transaction.add(R.id.fragment_container, fragments[index]);
        }
        transaction.show(fragments[index]);
        transaction.commit();
        currentTabIndex = index;
    }

    @Override
    public void back(View view) {
        super.back(view);
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANGED);
        intentFilter.addAction(Constant.ACTION_RESULT_LOCATION);
        intentFilter.addAction(Constant.ACTION_ON_INVITE_RECEIVED);
        intentFilter.addAction(Constant.ACTION_FOUND_COUPON);
        intentFilter.addAction(Constant.ACTION_NEW_COUPON);
        intentFilter.addAction(Constant.ACTION_CONTACT_GROUP_MODEL_CHANGED);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    //联系人变动，刷新联系人页面
                    case Constant.ACTION_CONTACT_CHANGED:

                        if (gaoDeMapFragment != null) {
                            gaoDeMapFragment.refresh();
                        }
                        if (conversationListFragment != null) {
                            conversationListFragment.refresh();//对会话列表也做刷新，因为联系人状态是判断是否能给对方发信息的依据
                        }

                        break;

                    case Constant.ACTION_CONTACT_GROUP_MODEL_CHANGED:
                        if (gaoDeMapFragment != null) {
                            gaoDeMapFragment.onContactGroupModelChange();
                        }
                        break;

                    case Constant.ACTION_RESULT_LOCATION:
                        // showToast("接收到定位了，，，，");
                        gaoDeMapFragment.createUserLocationMaker(intent);

                        break;

                    case Constant.ACTION_FOUND_COUPON:
                    case Constant.ACTION_NEW_COUPON:
                        gaoDeMapFragment.receivePushTopic(intent);
                        break;

                    case Constant.ACTION_ON_INVITE_RECEIVED:
                        String channelID = intent.getStringExtra("channelID");
                        String account = intent.getStringExtra("account");
                        String extra = intent.getStringExtra("extra");
                        Log.d(TAG, "agora：收到邀请 " + account);

                        //先判断是否有VideoChatViewActivity被打开，有打开，我们认为正在通话中，这种情况下，拒绝通话邀请，并携带 busy 信息
                        if (Helper.getInstance().isStartingCall()) {
                            InviteExtraInfo extraInfo = new InviteExtraInfo();
                            extraInfo.setType("busy");
                            // MyApplication.getInstance().getmAgoraAPI().channelInviteRefuse(channelID, account, 0, JSONObject.toJSONString(extraInfo));
                            return;
                        }

                        InviteExtraInfo info = JSONObject.parseObject(extra, InviteExtraInfo.class);
                        Intent intent1 = new Intent(MainActivity.this, VideoChatViewActivity.class);
                        intent1.putExtra("targetUserInfo", Helper.getInstance().getContactUserInfo(account))
                                .putExtra("type", info.getType())
                                .putExtra("isHadReceive", true)
                                .putExtra("channelID", channelID);

                        isStartingCall = true;
                        Helper.getInstance().setStartingCall(false);
                        startActivity(intent1);
                        break;


                }
            }
        }

        ;
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }


    private void unregisterBroadcastReceiver() {
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }


    @Override
    protected void onStart() {
        super.onStart();
        //  mMyOrientationListener.start();
        requestPermissions();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JzvdStd.resetAllVideos();
        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
        unregisterBroadcastReceiver();
        IMSClientBootstrap.getInstance().clearListener();

    }

    /**
     * 更新未读标签，显示小红点
     */
    public void updateUnreadLabel(int totalUnReadCount) {

        if (totalUnReadCount > 0) {
            bottomBar.setBadgeCount(totalUnReadCount);
        } else {
            bottomBar.removeBadge();
        }
    }

    //主动读取未读总数
    public void updateUnreadLabel() {
        updateUnreadLabel(IMSClientBootstrap.getInstance().getTotalUnReadCount());
    }


    @Override
    public void onResume() {
        super.onResume();
        Jzvd.goOnPlayOnResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_LOCK, isAccountLock);
        super.onSaveInstanceState(outState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (bottomTopicListV1.hide()) {
                return true;
            }
            if (currentTabIndex == 0 && gaoDeMapFragment.onBackClick()) {
                return true;
            }
            moveTaskToBack(false);
            //return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * show the dialog when user logged into another device
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        Helper.getInstance().logout();
        if (!MainActivity.this.isFinishing()) {
            // clear up global variables


            ConfirmDialog dialog = new ConfirmDialog(MainActivity.this, getString(R.string.Logoff_notification), getString(R.string.connect_conflict));
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    conflictBuilder = null;
                    finish();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            dialog.setCancelable(false);
            dialog.show();
            isConflict = true;

        }

    }


    private void showAccountLock() {
        isAccountLockDialogShow = true;
        Helper.getInstance().logout();
        if (!MainActivity.this.isFinishing()) {
            ConfirmDialog dialog = new ConfirmDialog(this, getString(R.string.Logoff_notification), getString(R.string.account_lock));
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    MyApplication.getInstance().finishActivities();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            dialog.setCancelable(false);
            dialog.show();
            isAccountLock = true;
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
            showConflictDialog();
        } else if (intent.getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountLockDialogShow) {
            showAccountLock();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //  PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);

    }


    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {

            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL) {
            gaoDeMapFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onGranted() {

    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        Log.i(TAG, "onDenied: 权限请求被拒绝");
    }

    public interface ChangeFragmentListener {
        void onChangeFragment();
    }

    private void updataUserInfo() {
        String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//        User loginUser = Helper.getInstance().getUserProfileManager().getLoginUserInfo();
        if (TextUtils.isEmpty(phoneNumber)) {
            ConfirmDialog confirmDialog = new ConfirmDialog(this, "提示", "还未绑定手机号，去绑定？", true);
            confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    startActivity(new Intent(MainActivity.this, UpdateUserInfoActivity.class));
                }
            });
            confirmDialog.show();
        }
    }


    @Override
    protected void onAccountChange() {
        super.onAccountChange();

        gaoDeMapFragment.refresh();
        if (conversationListFragment.isAdded()) {
            conversationListFragment.refresh();
        } else {
            Log.d(TAG, "onAccountChange: conversationListFragment 没有添加进activity");

        }
        if (profileFragment.isAdded()) {
            profileFragment.refresh();
        } else {
            Log.d(TAG, "onAccountChange: profileFragment 没有添加进activity");
        }
        // selectFragment(currentTabIndex);
    }
}

